﻿using System;
using System.Net.Sockets;
using System.Text;

namespace Common
{
    class SocketHelper
    {
        /// <summary>
        /// 维护人：梁家其
        /// 描述：Socket发送消息
        /// 引用的dll：System.Net.Sockets;
        /// 标签：Socket 套接字
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public string SendSocketMsg(string msg)
        {
            string response = "";
            Socket socket = null;
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect("发送的IP地址", 2323);
                if (socket.Connected)
                {
                    int count = socket.Send(Encoding.Default.GetBytes(msg));
                    if (count > 0)
                    {
                        byte[] buffer = new byte[10000];
                        socket.Receive(buffer, 0, 10000, SocketFlags.None);
                        response = Encoding.UTF8.GetString(buffer);
                    }
                }
            }
            catch (Exception)
            {
                throw new Exception();
            }
            finally
            {
                if (socket != null)
                {
                    socket.Close();
                }
            }
            return response;
        }
    }
}
